<template>
  <el-dialog
    v-if="isShow"
    :title="title"
    :visible.sync="isShow"
    :mode="mode"
    width="634px"
    :before-close="close"
  >
    <div class="leftTrrr">
      <el-autocomplete
        clearable
        style=" width: 260px; margin: 0 0 10px 20px"
        popper-class="tree-table-autocomplete"
        prefix-icon="el-icon-search"
        class="inline-input"
        v-model="seachData"
        placeholder="定位查找"
        @select="handleSelect"
        :fetch-suggestions="querySearch"
        :scrollBottom="handleScrollBottom"
      >
        <!-- :fetch-suggestions="querySearchAsync" -->
        <template slot-scope="{ item }">
          <slot :item="item"> </slot>
        </template>
      </el-autocomplete>
      <div class="treeBox">
        <el-tree
          :showLine="showLine"
          :load="loadNode"
          :props="props"
          :node-key="nodeKey"
          :default-expanded-keys="expandedKeys"
          lazy
          @node-click="handleNodeClick"
          @node-expand="showChildNode"
          :render-content="renderContent"
        >
        </el-tree>
      </div>
    </div>

    <div class="selected">
      <p class="yx">{{ selectedTitle }}({{ selected.length }})</p>
      <ul class="yixuanli">
        <template v-for="(item, index) in selected">
          <li class="yli" :key="index">
            <i
              style="margin-right: 5px"
              :style="{ color: selectedIconColor }"
              :class="setSelectedIcon(item)"
              @click="arrayRemove(selected, item)"
            ></i>
            <span class="yname">{{ item.name }}</span>
            <i
              class="el-icon-close mt"
              v-if="mode === 'checkbox'"
              @click="arrayRemove(selected, item)"
            ></i>
          </li>
        </template>
      </ul>
    </div>

    <div size="mini" type="default-mini" slot="footer" class="dialog-footer">
      <el-button size="mini" type="default-mini" @click="close">取消</el-button>
      <el-button size="mini" type="primary-font-mini" @click="confirm"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
// import { qryUnderOrg } from "@/api/util.js";

export default {
  name: "selectTree",
  props: {
    selectedTitle: {
      type: String,
      default: "已选成员"
    },
    title: {
      type: String,
      default: "未定义标题"
    },
    isShow: {
      type: Boolean,
      default: false
    },
    showLine: {
      type: Boolean,
      defualt: false
    },
    nodeKey: {
      type: String,
      default: "partyId"
    },
    props: {
      type: Object,
      default: () => {
        return {
          label: "abbrName",
          children: "child",
          isLeaf: "isLeaf"
        };
      }
    },

    requestTreeFunction: {
      type: Function
    },
    requestTreeParams: {
      type: Object
    },
    requestTreeParamConfig: {
      //接口请求映射表
      type: Object,
      default: function() {
        return { parentId: "partyId" };
      }
    },

    requestSeachFunction: {
      type: Function
    },
    requestSeachParams: {
      type: Object
    },
    requestSeachContent: {
      type: String,
      default: "branchName"
    },

    requestResultDataConfig: {
      type: String,
      default: "data"
    },
    selectlevel: {
      type: Number,
      default: 3
    },

    selectedIconColor: {
      type: String,
      default: "#0089EF"
    },

    setTreeICon: {
      type: Function,
      default: () => {}
    },

    setSelectedIcon: {
      type: Function,
      default: () => {}
    },
    selectedData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    mode: {
      validator: value => {
        return ["checkbox", "radio"].includes(value);
      },
      default: "checkbox"
    }
  },
  data() {
    return {
      seachData: "",
      expandedKeys: [],
      treeData: [],
      selected: [],
      firstCode: "",
      selectedCode: [],
      renderParams: {},
      resolve: Function,
      ishowTree: true,
      expandedlog: {},
      expandArr: []
    };
  },
  watch: {
    isShow(arr) {
      this.renderParams = this.requestTreeParams;
      this.selectedCode = [];
      this.expandArr = [];
      this.expandedKeys = [];
      this.selected = [];
    }
  },
  mounted() {},
  methods: {
    handleScrollBottom(data, callback) {
      let params = this.requestSeachParams;
      params[this.requestSeachContent] = this.seachData;
      this.requestSeachFunction(params).then(res => {
        let dataRows = res.data.data.rows;
        if (dataRows.length !== 0) {
          params.pageNo++;
          callback(dataRows);
        }
      });
    },
    handleSelect(seachItem) {
      if (this.mode === "radio") {
        this.selectedCode = [seachItem.autoCode];
        this.selected = [];
      } else {
        this.selectedCode.includes(seachItem.autoCode) ||
          this.selectedCode.push(seachItem.autoCode);
      }
      this.formatSelectedData(this.selectedCode);
      this.setIsSelected(this.expandArr);
    },

    querySearch(queryString, cb) {
      this.seachData = queryString;
      let params = this.requestSeachParams;
      params[this.requestSeachContent] = queryString;
      params.pageNo = 1;
      this.requestSeachFunction(params)
        .then(res => {
          cb(res.data.data.rows);
          params.pageNo++;
        })
        .catch(e => {
          console.log(e);
        });
    },

    formatSelectedData(arr) {
      if (arr.length < 0) {
        return false;
      }
      let firstCode = this.firstCode;
      arr.forEach(item => {
        let codeItem = item.split("-");
        let index = codeItem.indexOf(firstCode);
        let newcodeArr = codeItem.slice(index);
        let [lastItem] = newcodeArr.slice(-1);
        if (lastItem === "") {
          newcodeArr = newcodeArr.slice(0, -2);
        }
        newcodeArr.forEach(code => {
          if (!this.expandedKeys.includes(code)) {
            this.expandedKeys.push(code);
          }
        });
      });
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.requestTreeFunction(this.renderParams).then(res => {
          this.treeData = res.data[this.requestResultDataConfig];
          this.firstCode =
            this.treeData[0].partyId !== "" && this.treeData[0].partyId;
          if (this.selectedCode.length > 0) {
            this.formatSelectedData(this.selectedCode);
          } else {
            this.treeData.forEach(item => {
              this.expandedKeys.push(item.partyId);
            });
          }
          this.treeData.forEach(item => {
            this.expandedKeys.push(item.partyId);
          });
          this.expandArr.push(...this.treeData);
          resolve(this.treeData);
        });
      }

      if (node.level > 0) {
        let cloneParams = Object.assign({}, this.renderParams);
        for (let paramPropKey in this.requestTreeParamConfig) {
          let value = this.requestTreeParamConfig[paramPropKey];
          cloneParams[paramPropKey] = node.data[value];
        }
        this.requestTreeFunction(cloneParams).then(res => {
          let resolveData =
            res.data[this.requestResultDataConfig][0][this.props.children];
          this.setIsSelected(resolveData);
          this.expandArr.push(...resolveData);
          resolve(resolveData);
        });
      }

      // if (node.level === 1) {
      //   setTimeout(() => {
      //     let data = this.treeData[0].child;
      //     this.expandArr.push(...data)
      //     this.setIsSelected(data)
      //     resolve(data);
      //   }, 500);
      // }
    },

    close() {
      this.$emit("update:isShow", false);
    },

    confirm() {
      this.$emit("selectedStaffSuccess", this.selected);
      this.close();
    },
    renderContent(h, { node, data, store }) {
      let isSelectedHtml;
      if (data.isSelected) {
        isSelectedHtml = (
          <i class="el-icon-check" style="margin-right:15px"></i>
        );
      }

      return (
        <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
          <span>
            {this.setTreeICon(h, node, data, store)}
            <span>{node.label}</span>
          </span>
          <span>{isSelectedHtml}</span>
        </span>
      );
    },
    showChildNode(data, node) {},

    handleNodeClick(data, node, tree) {
      if (data.isLeaf && data.orgType === "2") {
        if (this.mode === "radio") {
          this.selected.forEach(item => (item.isSelected = false));
          this.selected = [data];
          data.isSelected = true;
        } else {
          if (!data.isSelected) {
            data.isSelected = true;
            this.selected.push(data);
            this.selectedCode.push(data.autoCode);
          } else {
            this.arrayRemove(this.selected, data);
          }
        }
      }
    },
    setIsSelected(arr) {
      arr.map(item => {
        if (this.selectedCode.includes(item.autoCode)) {
          item.isSelected = true;
          // if(){
          //
          // }else{
          //
          // }

          let reslut = this.selected.some(({ autoCode }, i, thisarr) => {
            if (autoCode === item.autoCode) {
              thisarr.splice(i, 1, item);
              return true;
            }
          });
          reslut || this.selected.push(item);
          // this.selected.includes(item) || this.selected.push(item)
        } else {
          item.isSelected = false;
        }
      });
    },
    arrayRemove(arr, delItem) {
      let condeIndex = this.selectedCode.indexOf(delItem.autoCode);
      this.selectedCode.splice(condeIndex, 1);
      delItem.isSelected = false;
      let index = arr.indexOf(delItem);
      arr.splice(index, 1);
    }
  }
};
</script>

<style scoped>
ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}
.yname {
  color: #4a4a4a;
}
.el-icon-close {
  float: right;
  cursor: pointer;
}
.yli {
  line-height: 18px;
  margin: 10px auto;
}
/deep/ .el-dialog__body {
  padding: 20px;
}

.el-tree >>> .is-leaf-org {
  padding-left: -10px;
  padding-right: 6px;
  color: #0089ef;
}

.custom-tree-node {
  width: 106px;
  height: 18px;
  font-size: 13px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(74, 74, 74, 1);
  line-height: 18px;
}

.leftTrrr {
  width: 300px;
  float: left;
  border: 1px solid #f1f1f1;
  padding-top: 10px;
}
.treeBox {
  height: calc(100vh - 360px);
  overflow: auto;
  padding: 0 12px;
}
.selected {
  float: right;
  border: 1px solid #f1f1f1;
  width: 270px;
}

.yx {
  color: #4a4a4a;
  font-size: 14px;
  padding: 10px 20px;
  border-bottom: 1px solid #f1f1f1;
  margin-bottom: 16px;
}
.yixuanli li {
  font-size: 14px;
  margin: 0;
  padding: 0 20px 12px 20px;
}
.yixuanli li:first-child {
  margin-top: 3px;
}
.mt {
  margin-top: 2px;
}
.yixuanli {
  height: calc(100vh - 366px);
  overflow: auto;
}
</style>
